var express = require('express')
var router = express.Router()
var SMSClient = require('@alicloud/sms-sdk')
var jwt = require('jsonwebtoken')
//导入两个token
let {refreshToken, accessToken, secret} = require('../utils/token')

var { loginModel, yzmModel, jiaoModel } = require('../model/models')
const tencentcloud = require('tencentcloud-sdk-nodejs-iai')
var multer = require('multer')



//登录
router.post('/deng', async (req, res) => {
    let phon = req.body.phon
    let data = await jiaoModel.findOne({ phon:phon })
    console.log(data)
    if (data) {
        let accessTokenData = accessToken({phon})
        let refreshTokenData = refreshToken({phon})
        res.send({
            data:data,
            code: 200,
            msg:"登录成功",
            accessToken:accessTokenData,
            refreshToken:refreshTokenData,
            data
        })
    } else {
        res.send({
            code: 404
        })
    }
})
//判断长token的接口
router.get("/refresh", async (req, res) => {
    //获取请求头中携带的长token
    let refreshtoken = req.headers.refreshtoken
    // 解析token
    jwt.verify(refreshtoken, secret, (err, data) => {
      //验证长token是否有效
      if (err) {
        //如果长token失效则返回401，前端会直接跳转回登陆页面
        res.send({
          code: 401,
          msg: '长token失效,请重新登录'
        })
      } else {
        //如果长token有效则刷新两个token的保存时长
        res.send({
          code: 200,
          msg: '刷新成功',
          accessToken: accessToken(),//刷新accessToken
          refreshToken: refreshToken() //刷新refreshToken
        })
      }
    })
  })
//注册
router.post('/zhuce', async (req, res) => {
    await loginModel.create(req.body)
    res.send({
        code: 200
    })
})




//短信
/* GET home page. */
function getCode() {
    let str = "";
    for (let i = 0; i < 6; i++) {
        str += parseInt(Math.random() * 10)
    }
    return str;
}

// 调用 http://localhost:3000/get_sms
router.post('/get_sms', function (req, res, next) {
    let phoneNum = req.body.phone;  //获取前端参数phone
    //初始化sms_client
    let smsClient = new SMSClient({
        accessKeyId: 'LTAI5tNHaRGBNBRxvksQVMQt',  //自己阿里云的accessKeyId
        secretAccessKey: '6phavFyrarzjNpEYaFQUK9iW4PvXok'  //自己阿里云的secretAccessKey
    });
    // 获取6位随机数
    let str = getCode();
    //session  -- str

    //   req.session.code =str; // 
    //   tel, code

    // 开始发送短信
    smsClient.sendSMS({
        PhoneNumbers: phoneNum,
        SignName: "小谷APP", //签名名称,阿里云注册
        TemplateCode: "SMS_474785291", //模版CODE,阿里云注册 
        TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
    }).then(r => {
        console.log('执行成功');
        console.log(phoneNum);
        console.log(str);


        let { Code } = r;
        if (Code == 'OK') {
            // 保存电话号码和验证码
            yzmModel.create({ phone: phoneNum, yzm: str })
            res.send({
                code: 0,
                msg: 'success',
                sms: str
            })
        }
    }).catch(err => {
        res.send({
            code: 1,
            err
        })
    })
});

router.post('/yzms', async (req, res) => {
    let yzms = req.body.yzms
    let data = await yzmModel.findOne({ yzm: yzms })
    if (data) {
        res.send({
            code: 200
        })
    } else {
        res.send({
            code: 404
        })
    }

})

// 配置 multer 的存储选项
const storage = multer.diskStorage({
    // destination: 定义文件的存储目录
    destination: function (req, file, cb) {
        // cb：回调函数，传入 null 表示没有错误，'uploads/' 为存储目录
        cb(null, 'uploads/') // 确保这个文件夹已经存在
    },
    filename: function (req, file, cb) {
        // cb：回调函数，传入文件字段名和当前时间戳作为文件名，使它保持唯一
        cb(null, file.fieldname + '-' + Date.now() + ".png")
    }
})
// 创建一个 multer 实例并配置存储选项
const upload = multer({ storage: storage })

//新增用户
router.post('/jiao', (req, res) => {
    jiaoModel.create(req.body)
    res.send({
        code: 200
    })
})

//人脸
router.post('/renlianshibie', async (req, res) => {
    const { b64 } = req.body
    const IaiClient = tencentcloud.iai.v20200303.Client
    const clientConfig = {
        credential: {
            secretId: 'AKIDVr1xjMo3JPODpFYhS4cK4c5sZM2d5QZV',
            secretKey: 'wfBVdaJq9ZoqgKkxxpZAZllcO13z6OZf'
        },
        region: 'ap-beijing',
        profile: {
            httpProfile: {
                endpoint: 'iai.tencentcloudapi.com'
            }
        }
    }
    const client = new IaiClient(clientConfig)

    const params = {
        'GroupIds': [
            '20040201'
        ],
        'Image': b64,
        'NeedPersonInfo': 1,
        'QualityControl': 0,
        'FaceMatchThreshold': 85,
    };
    try {
        let doc = await client.SearchFaces(params)
        if (doc.Results[0].Candidates.length != 0) {
            let personName = doc.Results[0].Candidates[0].PersonName
            res.send({
                code: 200,
                personName,
            })
        } else {
            res.send({
                code: 404,

            })
        }
    } catch (error) {
        res.send({
            code: 500,
            error: '服务器内部错误'
        })
    }

})



module.exports = router


